package leetcode;

/**
 * @author Cheng Jun
 * Description: 根据数组，创建 ListNode
 * @version 1.0
 * @date 2021/12/13 9:56
 */
public class ListNodeUtil {

    public static void main(String[] args) {
        System.out.println(getListNode(new int[]{}));
        System.out.println(getListNode(new int[]{1, 2, 3}));
        System.out.println(getListNodeByIter(new int[]{}));
        System.out.println(getListNodeByIter(new int[]{1, 2, 3}));
        System.out.println(getListNodeByRec(new int[]{}));
        System.out.println(getListNodeByRec(new int[]{1, 2, 3}));
    }

    /**
     * 根据 int 数组，创建 ListNode
     *
     * @param valArray
     * @return leetcode.ListNode
     * @author Cheng Jun
     * @date 2021/12/13 10:35
     */
    public static ListNode getListNode(int[] valArray) {
        int length = valArray.length;
        if (length == 0) return null;
        ListNode[] listNodes = new ListNode[length];
        // 创建ListNode 数组
        for (int i = 0; i < length; i++) {
            listNodes[i] = new ListNode(valArray[i]);
        }
        // 维护数组的后继节点
        for (int i = 0; i < length - 1; i++) {
            listNodes[i].next = listNodes[i + 1];
        }
        return listNodes[0];
    }

    /**
     * 迭代实现 根据 int 数组，创建 ListNode
     *
     * @param valArray
     * @return leetcode.ListNode
     * @author Cheng Jun
     * @date 2021/12/13 10:02
     */
    public static ListNode getListNodeByIter(int[] valArray) {
        ListNode nextNode = null;
        for (int i = valArray.length - 1; i >= 0; i--) {
            nextNode = new ListNode(valArray[i], nextNode);
        }
        return nextNode;
    }

    /**
     * 递归实现 根据 int 数组，创建 ListNode
     *
     * @param valArray
     * @return leetcode.ListNode
     * @author Cheng Jun
     * @date 2021/12/13 10:10
     */
    public static ListNode getListNodeByRec(int[] valArray) {
        return getNextListNode(valArray, 0);
    }

    private static ListNode getNextListNode(int[] valArray, int index) {
        if (index < valArray.length) {
            return new ListNode(valArray[index], getNextListNode(valArray, index + 1));
        } else {
            return null;
        }
    }
}
